package com.example.demo001.config;

import com.example.demo001.interceptor.UserInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;

/**
 * 配置类，注册web层相关组件
 */
@Configuration
public class WebMvcConfiguration extends WebMvcConfigurationSupport {

    private final UserInterceptor userInterceptor;

    // 使用构造函数注入
    public WebMvcConfiguration(UserInterceptor userInterceptor) {
        this.userInterceptor = userInterceptor;
    }

    /**
     * 注册自定义拦截器
     *
     */
    @Override
    protected void addInterceptors(InterceptorRegistry registry) {

        registry.addInterceptor(userInterceptor)
                .addPathPatterns("/user/**")
                .excludePathPatterns("/user/register")
                .excludePathPatterns("/user/login")
                .excludePathPatterns("/user/sendCode")
                .excludePathPatterns("/user/resetPassword")
                .excludePathPatterns("/user/isLogin/*");

    }

    @Bean
    public Docket docket1() {

        ApiInfo apiInfo = new ApiInfoBuilder()
                .title("这是项目接口文档标题")
                .version("2.1")
                .description("这是项目接口文档简介")
                .build();

        return new Docket(DocumentationType.SWAGGER_2)
                .groupName("接口")
                .apiInfo(apiInfo)
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.example.demo001.controller"))      //指定生成接口需要扫描的包
                .paths(PathSelectors.any())
                .build();
    }


    /**
     * 设置静态资源映射，主要是访问接口文档（html、js、css）
     *
     */
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        // "/doc.html"视作静态资源，而不是controller请求

        registry.addResourceHandler("/doc.html")
                .addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
    }


}